package io.renren.modules.oss.cloud;

import io.renren.common.exception.RRException;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author Chenjiacheng
 * @CREATE 20190218 15:13
 */
public class FileCloudStorageService extends CloudStorageService {

    public FileCloudStorageService( CloudStorageConfig config ){
        this.config = config;
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, config.getFilePath() + getTypePath( suffix ) + getFileName() + suffix );
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            //获取输出流
            OutputStream os = new FileOutputStream( path );
            //获取输入流 CommonsMultipartFile 中可以直接得到文件的流
            int temp;
            //一个一个字节的读取并写入
            while(( temp = inputStream.read() )!=(-1)) {
                os.write(temp);
            }
            os.flush();
            os.close();
            inputStream.close();

        } catch ( Exception e) {
            e.printStackTrace();
            throw new RRException("上传文件失败", e);
        }
        return config.getFileDomain() + path;
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, config.getFilePath() + getTypePath( suffix ) + getFileName() + suffix );
    }


    private String getTypePath( String suffix ){
        String path = "/res/file";
        if ( suffix == null ){
            return path;
        }
        String lower = suffix.toLowerCase();
        if( lower.equals(".png") || lower.equals(".jpg") || lower.equals(".jpeg") || lower.equals(".gif")  ){
            path = "/res/image";
        }else if( lower.equals(".mp4") || lower.equals(".mkv") || lower.equals(".avi") || lower.equals(".av") ){
            path = "/res/video";
        }
        return path;
    }

}
